from datetime import timedelta

from django.utils import timezone as dj_timezone
from django.utils.translation import gettext as _

from core import errors
from apps.app_kunyuan.models import KunYuanService
from apps.app_kunyuan.kunyuan_client import KunyuanClient
from apps.app_service.odc_manager import OrgDataCenterManager


class KunYuanServiceManager:
    @staticmethod
    def filter_kunyuan_service(odc_id: str = None):
        qs = KunYuanService.objects.all()
        if odc_id:
            qs = qs.filter(org_data_center_id=odc_id)

        return qs

    @staticmethod
    def update_service_version(service: KunYuanService):
        try:
            nt = dj_timezone.now()
            if not service.version_update_time or (nt - service.version_update_time) > timedelta(minutes=1):
                client = KunyuanClient(endpoint_url=service.endpoint_url, auth_username='', auth_password='')
                version = client.get_kunyuan_version()
                if version:
                    service.version = version
                    service.version_update_time = nt
                    service.save(update_fields=['version', 'version_update_time'])
        except Exception as exc:
            return exc

        return True

    @staticmethod
    def add_admin_to_kunyuan_service(service: KunYuanService, usernames: list[str]):
        auth_user = service.username
        auth_password = service.raw_password()

        if not (auth_user and auth_password):
            raise errors.Error(message=_('无法添加管理员权限到坤元服务，未配置认证用户和密码'))

        try:
            client = KunyuanClient(
                endpoint_url=service.endpoint_url, auth_username=auth_user, auth_password=auth_password)
            client.add_admins_to_kunyuan(usernames=usernames)
        except errors.Error as exc:
            raise errors.Error(message=_('添加管理员权限到坤元服务失败。') + str(exc))

    @staticmethod
    def remove_admin_from_kunyuan_service(service: KunYuanService, usernames: list[str]):
        auth_user = service.username
        auth_password = service.raw_password()

        if not (auth_user and auth_password):
            raise errors.Error(message=_('无法从坤元服务移除管理员权限，未配置认证用户和密码'))

        try:
            client = KunyuanClient(
                endpoint_url=service.endpoint_url, auth_username=auth_user, auth_password=auth_password)
            client.remove_admins_from_kunyuan(usernames=usernames)
        except errors.Error as exc:
            raise errors.Error(message=_('从坤元服务移除管理员权限失败。') + str(exc))

    @staticmethod
    def get_odc_admin_usernames(odc_id: str) -> list:
        objs = OrgDataCenterManager.get_odc_admin_and_ops_users_qs(odc_id=odc_id)
        return [u.userprofile.username for u in objs]
